package com.servlet;

import com.dao.UserDao;
import com.dao.implement.UserDaoImpl;
import com.model.User;
import com.utils.Md5Util;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

/**
 * @author Wray
 */
@WebServlet("/RegistServlet")
public class RegistServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //编码
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");

        String username = request.getParameter("username");
        String password = Md5Util.getmd5Str(request.getParameter("password"));
        String repeatPassword = Md5Util.getmd5Str(request.getParameter("repeatPassword"));
        //第二次密码
        //trim判断是否有空格
        if(username==null||username.trim().isEmpty()){
            request.setAttribute("registError", "用户名不能为空");
            request.getRequestDispatcher("regist.jsp").forward(request, response);
            return;
        }

        if(password==null||password.trim().isEmpty()){
            request.setAttribute("registError", "密码不能为空");
            request.getRequestDispatcher("regist.jsp").forward(request, response);
            return;
        }

        if(!password.equals(repeatPassword)){
            request.setAttribute("registError", "两次密码不一致");
            request.getRequestDispatcher("regist.jsp").forward(request, response);
            return;
        }

        UserDao userDao=new UserDaoImpl();
        User user=new UserDaoImpl().selectByUsername(username);
        if(user!=null){
            request.setAttribute("registError", "该用户名已存在");
            request.getRequestDispatcher("regist.jsp").forward(request, response);
        }else {
            if(userDao.register(username,password)){
                response.sendRedirect("login.jsp");
            }else {
                request.setAttribute("registError", "注册失败，发生未知错误");
                request.getRequestDispatcher("regist.jsp").forward(request, response);
            }
        }

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
